<template>
  <div>
    <el-form ref="dataForm" :model="formData" label-position="right" class="product-attr">
      <el-button size="small" type="primary" @click="handleAdd">添加</el-button>
      <el-card v-for="(item, index) in formData" :key="index" class="product-attr-box" shadow="never">
        <template #header>
          <div class="product-attr-close">
            <IconifyIconOffline style="cursor: pointer" icon="ep:close" @click="handleDelete(index)" />
          </div>
          <el-form-item :prop="[String(index), 'name']" :rules="[{ required: true, message: '属性名不能为空' }]">
            <m-autocomplete
              v-model="formData[index].name"
              class="product-attr-name"
              :suggestionValues="suggestions"
              placeholder="属性名"
              :elAutocomplete="{ 'popper-class': 'product-attr-autocomplete' }"
              @input="attrChange(item)"
              @select="item => handleAttrSelect(item, index)"
            />
          </el-form-item>
        </template>
        <el-row v-for="(value, valueIndex) in item.value" :key="valueIndex" :gutter="10" class="product-attr-row">
          <el-col :span="22">
            <el-form-item
              :rules="[{ required: true, message: '属性值不能为空' }]"
              :prop="[String(index), 'value', String(valueIndex), 'attrValue']"
            >
              <el-autocomplete
                v-model="formData[index].value[valueIndex].attrValue"
                :fetch-suggestions="(queryString: string, cb: any) => queryAttrValue(queryString, cb, index)"
                clearable
                placeholder="属性值"
                @input="attrChange(item)"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="item.value.length > 1" :span="1" class="product-attr-row-inline cursor-pointer">
            <IconifyIconOffline icon="ep:delete" @click="handleDeleteValue(valueIndex, item)" />
          </el-col>
          <el-col :span="1" class="product-attr-row-inline cursor-pointer">
            <IconifyIconOffline icon="ep:circle-plus" @click="handleAddValue(valueIndex, item)" />
          </el-col>
        </el-row>
      </el-card>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { getDictTree } from "@/api/system/dictApi";
import { PropType, ref, shallowReactive, shallowRef, useTemplateRef } from "vue";
import { useSubmitFormItem, buildSubmitFormItem, MSingleUpload, MAutocomplete } from "page-com";
import { accessTree } from "@/utils/tree";
const dataFormRef = useTemplateRef("dataForm");
const formData = defineModel<ShopProductAttrAddVo[]>();
const addSubmitFormItem = useSubmitFormItem();
const { validate, clear, getData, getKeys } = buildSubmitFormItem(formData, dataFormRef);
let suggestions: ShopDictTreeVo[] = [];
let valTpl = [];
let dicts = new Map<string, ShopDictTreeVo[]>();
let attrMap = new Map<number, any>();
getDictTree("商品属性").then(v => {
  if (RESPONSE_CODE.SUCCESS == v.code) {
    suggestions = v.data.find(val => val.value == "商品属性")?.children ?? [];
    accessTree(suggestions, v => dicts.set(v.value, v.children));
  }
});

const queryAttrValue = (queryString: string, cb: any, index: number) => {
  let tpl = dicts.get(attrMap.get(index));
  const results = queryString ? (tpl ?? []).filter(createFilter(queryString)) : tpl;
  cb(results);
};
const createFilter = (queryString: string) => {
  return (restaurant: { value: string }) => {
    return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
  };
};
const handleAdd = () => {
  formData.value.push({ name: "", value: [{ attrName: "", attrValue: "" }] });
};
const handleDelete = (index: number) => {
  formData.value.splice(index, 1);
};
function getArrData() {
  return { attrs: getData() };
}
defineExpose({ clear, getData, validate });
addSubmitFormItem({ clear, getData: getArrData, validate, getKeys });
function handleDeleteValue(index: number, item: ShopProductAttrAddVo) {
  item.value.splice(index, 1);
}
function handleAddValue(index: number, item: ShopProductAttrAddVo) {
  item.value.splice(index + 1, 0, { attrName: "", attrValue: "" });
}
function attrChange(item: ShopProductAttrAddVo) {
  if (item.name) {
    item.value.forEach(val => {
      val.attrName = item.name;
    });
  }
}
function handleAttrSelect(value: { meta: [] }, index: number) {
  attrMap.set(index, value.meta[value.meta.length - 1]);
}
</script>
<style lang="scss">
.product-attr-tplsel {
  font-size: small;
}
.product-attr-close {
  display: flex;
  justify-content: flex-end;
  font-size: 20px;
  margin-bottom: 10px;
}
.product-attr-name {
  width: 30%;
}
.product-attr-box {
  margin-top: 10px;
}
.product-attr-row {
  width: 50%;
}
.product-attr-row-inline {
  height: 32px;
  align-self: flex-start;
  text-align: center;
  display: flex !important;
  flex-direction: column;
  justify-content: center;
}
.product-attr-autocomplete li {
  line-height: normal;
}
</style>
